package com.self.cloudmall.oms.config;

import com.self.cloudmall.oms.interceptor.ValidUserLoginInterceptor;
import feign.RequestInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.HttpServletRequest;

@Configuration
public class OrderMvcConfig implements WebMvcConfigurer {

    @Autowired
    private ValidUserLoginInterceptor validUserLoginInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(validUserLoginInterceptor).addPathPatterns("/**");
    }

    /**
     *  获取其他服务threadlocal的当前用户，为空，是因为feign新建requestTemp，没有吧header
     *  想下传递，所以获取不到cookie
     * @return
     */
    @Bean
    public RequestInterceptor requestInterceptor(){
        return requestTemp -> {
            //获取request
            RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
            if (requestAttributes != null){
                HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
                //把老的请求头cookie赋值给新的requestTemplate
                requestTemp.header("Cookie",request.getHeader("Cookie"));
            }
        };
    }
}
